#include "StdAfx.h"
#include "SinistarMachine.h"
#include "apu/hc55516/hc55516.h"

CSinistarMachine::CSinistarMachine()
{
}

CSinistarMachine::~CSinistarMachine()
{
}

int CSinistarMachine::Init()
{
CWilliamsMachine::Init();
MainCPU->SetOp(ReadMainCPU);
MainCPU->SetRead(ReadMainCPU);
MainCPU->SetWrite(WriteMainCPU);
PIA[2]->OutputCA2Func = OutputCA2;
PIA[2]->OutputCB2Func = OutputCB2;
hc55516_sh_start();
return(0);
}

void CSinistarMachine::Reset()
{
CWilliamsMachine::Reset();
Sound->SetCallback(ProcessSound);
}

void CSinistarMachine::Line(u32 mainc,u32 soundc,int irq)
{
CWilliamsMachine::Line(mainc,soundc,irq);
}

void CSinistarMachine::SaveState(CState *s)
{
CWilliamsMachine::SaveState(s);
}

void CSinistarMachine::LoadState(CState *s)
{
CWilliamsMachine::LoadState(s);
}

void CSinistarMachine::ProcessSound(void *user,void *data,int len)
{
s16 *dest = (s16*)data;
s16 buf[2][1024*2];
int i;

if(user)
	{
	hc55516_update(0,buf[0],len);
	((CSinistarMachine*)user)->DAC->Update(0,buf[1],len);
	for(i=0;i<len;i++)
		dest[i] = ((buf[0][i] * 5) + (buf[1][i] * 3)) / 8;
	}
}

u8 CSinistarMachine::ReadMainCPU(void *user,u32 addr)
{
CSinistarMachine *M = (CSinistarMachine*)user;

switch(addr & 0xF000)
	{
	case 0xD000:
		if(M->RomSet->GetFlags() & F_PLAYBALL)
			break;
		return(M->SinistarRAM[addr & 0xFFF]);
	}
return(CWilliamsMachine::ReadMainCPU(user,addr));
}

void CSinistarMachine::WriteMainCPU(void *user,u32 addr,u8 data)
{
CSinistarMachine *M = (CSinistarMachine*)user;

switch(addr & 0xF000)
	{
	case 0xC000:
		if(addr >= 0xCC00)					//nvram write
			{
			M->NVRAM[addr & 0x3FF] = data;
			return;
			}
		break;
	case 0xD000:
		if(M->RomSet->GetFlags() & F_PLAYBALL)
			break;
		M->SinistarRAM[addr & 0xFFF] = data;
		return;
	}
CWilliamsMachine::WriteMainCPU(user,addr,data);
}

void CSinistarMachine::OutputCA2(void *user,u8 data)
{
hc55516_digit_w(0,data);
}

void CSinistarMachine::OutputCB2(void *user,u8 data)
{
hc55516_clock_w(0,data);
}
